<template>
    <div class="saleFunnel">
        <Modal v-model="customerDetailModal" :scrollable="true"
               :width="customerDetailModalWidth" :mask="false" :styles="{marginLeft: '70px',marginTop:'30px'}" class="customerDetailModalClass"  @on-visible-change="getPipeLineByLevelReport()">
            <p slot="header">客戶基本信息</p>
            <div slot="footer"></div>
            <customer-details :customerId="customerId" :customerCreditCode="creditCode" :type="customerType"></customer-details>
        </Modal>
        <div class="homeMain-title">
            PIPELINE报表
        </div>
        <Row :gutter="16" class="mt-10">
            <Col span="8">

                <div class="saleFunnel-title">销售漏斗</div>

                <div class="right-title">
                    <treeselect v-model="saleFunnelModel"
                        :searchable="false"
                        placeholder="请选择"
                        :options="saleFunnelModelList"
                        :default-expand-level="999"
                        style="width:150px"/>
                </div>


                <div class="saleFunnelPic">
                    <ul>
                        <li :style="{'height': item.unitHeight + 'px'}" v-for="(item, index) in saleFunnelPicData" :key="index" @click="checkCurrentSaleFunnelPic(item.id)">
                            <div class="data2" :style="{'width': item.width + 'px', 'background-color': item.color, 'height': item.unitHeight + 'px'}">
                                <div class="leftArr" :style="{'border-top-width': item.unitHalfHeight + 'px', 'border-right-width': item.topborderWidth + 'px', 'border-bottom-width': item.unitHalfHeight + 'px', 'border-left-width': item.topborderWidth + 'px', 'border-top-color': item.color, 'border-right-color': item.color}">
                                </div>
                                <div class="rightArr" :style="{'border-top-width': item.unitHalfHeight + 'px', 'border-right-width': item.topborderWidth + 'px', 'border-bottom-width': item.unitHalfHeight + 'px', 'border-left-width': item.topborderWidth + 'px', 'border-top-color': item.color, 'border-left-color': item.color}">
                                </div>
                            </div>
                            <div class="data3" :style="{'height': item.unitHeight + 'px', 'line-height': item.unitHeight + 'px'}">{{item.levelName}} {{item.customerCount ? item.customerCount : 0}}/{{item.limitNum ? item.limitNum : 0}}</div>
                        </li>
                    </ul>
                    <div class="botText" @click="gotoCustomerListPage">
                        查看全部
                    </div>
                </div>

            </Col>
            <Col span="16">
                <div class="saleFunnel-title">PIPELINE客户明细表</div>


                <div class="right-title">
                    <div class="left-info">
                        <Select
                            placeholder="请选择客户等级"
                            @on-change="changeCustomerLevel"
                            v-model="customerLevelModel"
                            style="width:150px"
                            class="mr-10">
                            <Option v-for="(item, index) in customerLevelModelList" :value="item.id" :label="item.levelName" :key="index">{{ item.levelName }}</Option>
                        </Select>

                        <!-- <Select
                            @on-change="changeTimeScreening"
                            v-model="timeScreeningModel"
                            class="mr-10">
                            <Option v-for="(item, index) in timeScreeningModelList" :value="item.code" :label="item.name" :key="index">{{ item.name }}</Option>
                        </Select> -->
                    </div>

                    <div class="right-info">
                        <p>预计签约总额：{{totalContract}}</p>
                        <p class="ml-30">PIPELINE总额：{{totalContract2}}
                        <span class="span-sty2 ml-30">单位：万元</span></p>
                    </div>
                </div>

                <div class="right-table">
                    <Table2  storageKey="reportCustomerListTable" :columns="customerDetailColumns" :data="customerDetailData" height="280">
                    </Table2>
                    <!-- <div @click="goToBacklogModuleList" class="newMoreStyle">
                        查看更多>
                    </div> -->
                    <Page
                        :total="totalElements"
                        :page-size="size"
                        @on-change="changePage"
                        @on-page-size-change="changePageSize"
                        show-total
                        class="ta-c"></Page>
                </div>
            </Col>
        </Row>
        <Spin size="large" fix v-show="showSpin">
            {{spinMsg}}
        </Spin>
    </div>
</template>

<script>
    import Treeselect from '@riophae/vue-treeselect';
    import '@riophae/vue-treeselect/dist/vue-treeselect.css';
    import base64 from '@/libs/tool/base64';
    import Table2 from '@/pages/components/table';
    import util from '@/libs/util';
    import customerDetails from '@/customer/pages/customerDetails';
    export default {
        inject: ['reload'],
        name: 'saleFunnel',
        components: { Treeselect,
        Table2,
            customerDetails },
        data () {
            return {
                showSpin: false,
                spinMsg: '加载中，请稍后...',
                // 图标下拉选选中ID
                saleFunnelModel: 0,
                // 需要渲染的销售等级数据
                reportLevelList: [],
                customerLevelModel: 'all',
                // timeScreeningModel: 'all',
                saleFunnelModelList: [],
                customerLevelModelList: [
                    {
                        id: '',
                        levelName: ''
                    }
                ],
                customerId: '',
                creditCode: '',
                customerType: '',
                customerTableHeight: 520,
                customerDetailModal: false,
                customerDetailModalWidth: util.getContentWidth(),
                customerDetailModalHeight: util.getTableHeight(),
                // timeScreeningModelList: [
                //     {
                //         code: 'all',
                //         name: '全部'
                //     },
                //     {
                //         code: 'currentYear',
                //         name: '本年'
                //     },
                //     {
                //         code: 'halfYear',
                //         name: '近半年'
                //     },
                //     {
                //         code: 'currentQuarter',
                //         name: '本季度'
                //     },
                //     {
                //         code: 'currentMonth',
                //         name: '本月'
                //     }
                // ],
                saleFunnelPicData: [],
                customerDetailData: [],
                customerDetailColumns: [
                    {
                        title: '业务员',
                        key: 'userName',
                        ellipsis: true,
                        // align: 'center',
                        // fixed: 'left',
                        // width: 120,
                        render: (h, params) => {
                            return h('span', {
                                props: {

                                }
                            }, params.row.ownerUser.userName);
                        }
                    },
                    {
                        title: '企业名称',
                        key: 'name',
                        ellipsis: true,
                        // align: 'center',
                        // width: 250,
                        render: (h, params) => {
                            return h('span', {
                                attrs: {
                                    title: params.row.name
                                },
                                on: {
                                    click: () => {
                                        this.viewWorkflow(params.row);
                                    }
                                },
                                style: {
                                    cursor: 'pointer'
                                }
                            }, params.row.name);
                        }
                    },
                    {
                        title: '预计签约时间',
                        key: 'predictSignTime',
                        ellipsis: true
                        // align: 'center',
                        // width: 150,
                    },
                    {
                        title: '预计签约金额',
                        key: 'predictSignMoney',
                        ellipsis: true,
                        // align: 'center',
                        // width: 120,
                        render: (h, params) => {
                            return h('span', {
                                props: {

                                }
                            }, params.row.predictSignMoney ? params.row.predictSignMoney + '万元' : '');
                        }
                    },
                    {
                        title: '把握度',
                        key: 'powerPercent',
                        ellipsis: true,
                        // align: 'center',
                        // width: 120,
                        render: (h, params) => {
                            return h('span', {
                                props: {

                                }
                            }, params.row.powerPercent ? params.row.powerPercent + '%' : '');
                        }
                    },
                    {
                        title: 'PIPELINE金额',
                        key: 'pipelineMoney',
                        ellipsis: true,
                        // align: 'center',
                        // width: 120,
                        render: (h, params) => {
                            return h('span', {
                                props: {

                                }
                            }, params.row.pipelineMoney ? params.row.pipelineMoney + '万元' : '');
                        }
                    },
                    {
                        title: '渠道来源',
                        key: 'resourceName',
                        ellipsis: true,
                        // align: 'center',
                        // width: 100,
                        render: (h, params) => {
                            return h('span', {

                            }, params.row.resourceName ? params.row.resourceName : '暂无');
                        }
                    }
                ],
                totalElements: 1,
                page: 0,
                size: 5,
                totalContract: '',
                totalContract2: '',
                // 当前查询的用户列表
                userList: [],
                customerLevelId: '',
                timeRange: '',
                transferMod: false,
                transferModLoading: false,
                data1: [],
                targetKeys1: []
            };
        },
        mounted () {
            this.getFindAllChildrenUserListByUserIdForSalesReport();
        },
        watch: {
            saleFunnelModel (newValue, oldValue) {
                if (newValue && oldValue != 0) {
                    this.changeSaleFunnel(newValue);
                }
            }
        },
        methods: {
            gotoCustomerListPage () {
                // 获取当前用户是否存在下属员工
                depot.get({
                    url: this.URL.USER.FIND_CHILDREN_USER_LIST_BY_USER_ID,
                    cb: (data) => {
                        this.showSpin = false;
                        if (data.code === 0) {
                            this.childrenUserList = data.data;
                            let isManager;
                            // 长度大于0就是领导
                            if (this.childrenUserList && this.childrenUserList.length > 0) {
                                isManager = true;
                            } else {
                                isManager = false;
                            }
                            // 获取菜单，判断当前用户是否有客户的权限
                            let menusStr = sessionStorage.getItem('menus');
                            if (menusStr) {
                                let menus = JSON.parse(menusStr);
                                if (menus && menus.length > 0) {
                                    if (isManager) {
                                        if (this.checkExist(menus, 'manageCustomerList')) {
                                            this.$router.push({
                                                name: 'manageCustomerList'
                                            });
                                        } else {
                                            this.$Message.error('暂无权限');
                                        }
                                    } else {
                                        if (this.checkExist(menus, 'customerList')) {
                                            this.$router.push({
                                                name: 'customerList'
                                            });
                                        } else {
                                            this.$Message.error('暂无权限');
                                        }
                                    }
                                }
                            }
                        } else if (data.code === 999) {
                            this.$Message.error(data.message);
                        }
                    },
                    ce: (error) => {
                        this.showSpin = false;
                    }
                });
            },
            checkExist (menuList, link) {
                let hasExist = false;
                if (!menuList || !link) {
                    return hasExist;
                }
                menuList.forEach(item => {
                    if (item && !hasExist) {
                        if (item.link == link) {
                            hasExist = true;
                        } else {
                            if (item.children) {
                                hasExist = this.checkExist(item.children, link);
                            }
                        }
                    }
                });
                return hasExist;
            },
            // 获取漏斗模型下拉
            getFindAllChildrenUserListByUserIdForSalesReport () {
                this.showSpin = true;
                let now = new Date();
                depot.get({
                    url: this.URL.CUSTOMER.SALES_BY_LEVEL_REPORT,
                    cb: (data) => {
                        console.log(new Date().getTime() - now.getTime());
                        this.showSpin = false;
                        if (data.code === 0) {
                            this.saleFunnelModelList = data.data;
                            this.findDefaultValue(data.data);
                            this.getSaleFunnelPicData();
                            this.getPipeLineByLevelReport();
                            this.getPipeLineSignTotalAmountReport();
                            this.getPipeLineTotalAmountReport();
                        } else {
                            this.$Message.error(data.message);
                        }
                    },
                    ce: (error) => {
                        this.showSpin = false;
                        this.$Message.error('获取漏斗模型下拉失败');
                    }
                });
            },
            // 获取默认值
            findDefaultValue (options) {
                if (options) {
                    for (let i = 0; i < options.length; i++) {
                        if (this.saleFunnelModel) {
                            break;
                        }
                        let option = options[i];
                        if (!option) {
                            continue;
                        }
                        if (option.isDefault) {
                            this.saleFunnelModel = option.id;
                            this.userList = option.userList;
                            this.reportLevelList = option.reportLevelList;
                        } else {
                            this.findDefaultValue(option.children);
                        }
                    }
                }
            },
            // 选择销售漏斗模型方法
            changeSaleFunnel (val) {
                console.log(val);
                this.userList = '';
                this.customerLevelId = '';
                this.timeRange = '';
                this.totalElements = 1;
                this.page = 0;
                this.size = 5;
                this.customerLevelModel = 'all';
                // this.timeScreeningModel = 'all';
                this.findSameValue(this.saleFunnelModelList, val);
                this.getSaleFunnelPicData();
                this.getPipeLineByLevelReport();
                this.getPipeLineSignTotalAmountReport();
                this.getPipeLineTotalAmountReport();
            },
            // 获取默认值
            findSameValue (options, id) {
                if (options && id) {
                    for (let i = 0; i < options.length; i++) {
                        let option = options[i];
                        if (!option) {
                            continue;
                        }
                        if (option.id == id) {
                            this.userList = option.userList;
                            this.reportLevelList = option.reportLevelList;
                        } else {
                            this.findSameValue(option.children, id);
                        }
                    }
                }
            },
            // 获取销售漏斗数据
            getSaleFunnelPicData () {
                if (this.reportLevelList && this.reportLevelList.length > 0) {
                    this.showSpin = true;
                    // 客户等级
                    this.customerLevelModelList = [];
                    let obj = {
                        id: 'all',
                        levelName: '全部'
                    };
                    this.customerLevelModelList.push(obj);
                    this.customerLevelModelList = this.customerLevelModelList.concat(this.reportLevelList);
                    this.saleFunnelPicData = [];
                    this.saleFunnelPicData = this.saleFunnelPicData.concat(this.reportLevelList);
                    // 自定义最大宽度
                    let maxWidth = 310;
                    // 自定义最小宽度
                    let minWidth = 60;
                    // 自定义整体高度
                    let allHeight = 165;
                    // 根据PSD长宽根据三角公式自定义角度
                    let tanA = 0.7222;
                    // 数组个数
                    let lenNum = this.saleFunnelPicData.length;
                    // 标准高度
                    let unitHeight = allHeight / lenNum;
                    // 三角形短边宽度
                    let topborderWidth = unitHeight * tanA;
                    // 根据最大宽度算出最大宽度底部宽度
                    let maxBottomWidth = maxWidth - topborderWidth * 2;
                    // 每次递减宽度
                    let decrementWidth;
                    if(lenNum > 1){
                        decrementWidth = (maxBottomWidth - minWidth) / (lenNum - 1);
                    }else{
                        decrementWidth = 0;
                    }
                    this.saleFunnelPicData.forEach((item, index) => {
                        // 标准高度赋值
                        item.unitHeight = parseInt(unitHeight - 5);
                        // 三角形长边高度
                        item.unitHalfHeight = parseInt((unitHeight - 5) / 2);
                        // 三角形短边高度
                        item.topborderWidth = parseInt(topborderWidth / 2);
                        // 每一行宽度 根据 decrementWidth 值 和index 还有 数据比例 递减
                        item.width = parseInt((maxBottomWidth - decrementWidth * index) * (item.customerCount / item.limitNum));
                    });
                    this.$forceUpdate();
                    this.showSpin = false;
                }
            },
            // pipeLine明细数据
            getPipeLineByLevelReport () {
                this.showSpin = true;
                let queryParams = {};
                if (this.userList) {
                    queryParams.userIdList = '';
                    this.userList.forEach(item => {
                        queryParams.userIdList = queryParams.userIdList + item + ',';
                    });
                }
                if (this.customerLevelId) {
                    queryParams.customerLevelId = this.customerLevelId;
                }
                if (this.timeRange) {
                    queryParams.timeRange = this.timeRange;
                }
                queryParams.page = this.page;
                queryParams.size = this.size;
                depot.get({
                    url: this.URL.CUSTOMER.PIPE_LINE_BY_LEVEL_REPORT,
                    config: {
                        params: queryParams
                    },
                    cb: (data) => {
                        this.showSpin = false;
                        if (data.code === 0) {
                            if (data.data.content.length > 5) {
                                this.customerDetailData = data.data.content.slice(0, 5);
                            } else {
                                this.customerDetailData = data.data.content;
                            }

                            this.size = data.data.size;
                            this.totalElements = data.data.totalElements;
                        } else {
                            this.$Message.error(data.message);
                        }
                    },
                    ce: (error) => {
                        this.showSpin = false;
                        this.$Message.error('pipeLine明细数据失败');
                    }
                });
            },
            // pipeLine签约总额数据
            getPipeLineSignTotalAmountReport () {
                this.showSpin = true;
                let queryParams = {};
                if (this.userList) {
                    queryParams.userIdList = '';
                    this.userList.forEach(item => {
                        queryParams.userIdList = queryParams.userIdList + item + ',';
                    });
                }
                if (this.customerLevelId) {
                    queryParams.customerLevelId = this.customerLevelId;
                }
                if (this.timeRange) {
                    queryParams.timeRange = this.timeRange;
                }
                depot.get({
                    url: this.URL.CUSTOMER.PIPE_LINE_SIGN_TOTAL_AMOUNT_REPORT,
                    config: {
                        params: queryParams
                    },
                    cb: (data) => {
                        this.showSpin = false;
                        if (data.code === 0) {
                            this.totalContract = data.data;
                        } else {
                            this.$Message.error(data.message);
                        }
                    },
                    ce: (error) => {
                        this.showSpin = false;
                        this.$Message.error('pipeLine签约总额数据失败');
                    }
                });
            },
            // pipeLine总额数据
            getPipeLineTotalAmountReport () {
                this.showSpin = true;
                let queryParams = {};
                if (this.userList) {
                    queryParams.userIdList = '';
                    this.userList.forEach(item => {
                        queryParams.userIdList = queryParams.userIdList + item + ',';
                    });
                }
                if (this.customerLevelId) {
                    queryParams.customerLevelId = this.customerLevelId;
                }
                if (this.timeRange) {
                    queryParams.timeRange = this.timeRange;
                }
                depot.get({
                    url: this.URL.CUSTOMER.PIPE_LINE_TOTAL_AMOUNT_REPORT,
                    config: {
                        params: queryParams
                    },
                    cb: (data) => {
                        this.showSpin = false;
                        if (data.code === 0) {
                            this.totalContract2 = data.data;
                        } else {
                            this.$Message.error(data.message);
                        }
                    },
                    ce: (error) => {
                        this.showSpin = false;
                        this.$Message.error('pipeLine总额数据失败');
                    }
                });
            },
            // 选择客户等级方法
            changeCustomerLevel (val) {
                if (val === 'all') {
                    this.customerLevelId = '';
                } else {
                    this.customerLevelId = val;
                }
                this.totalElements = 1;
                this.page = 0;
                this.size = 5;
                this.getPipeLineByLevelReport();
                this.getPipeLineSignTotalAmountReport();
                this.getPipeLineTotalAmountReport();
            },
            // 选择时间方法
            // changeTimeScreening (val) {
            //     if (val === 'all') {
            //         this.customerLevelId = '';
            //     } else {
            //         this.timeRange = val;
            //     }
            //     this.totalElements = 1;
            //     this.page = 0;
            //     this.size = 10;
            //     this.getPipeLineByLevelReport();
            //     this.getPipeLineSignTotalAmountReport();
            //     this.getPipeLineTotalAmountReport();
            // },
            // 点击当前销售漏斗
            checkCurrentSaleFunnelPic (val) {
                this.changeCustomerLevel(val);
                this.customerLevelModel = val;
            },
            // 翻页
            changePage (val) {
                this.page = val - 1;
                this.getPipeLineByLevelReport();
            },
            // 修改页面数据量
            changePageSize (val) {
                this.size = val;
                this.getPipeLineByLevelReport();
            },
            // 查看基本信息跳转
            viewWorkflow (data) {
                if (!data.id && !data.creditCode) {
                    this.$Message.error('获取公司详情失败');
                } else {
                    if (!data.id) {
                        this.customerId = null;
                    } else {
                        this.customerId = base64.encode(data.id + '');
                    }
                    this.customerType = 'viewing';
                    this.isManage = false;
                    this.customerDetailModal = true;
                }
            },
            // 穿梭框显示文字
            render1 (item) {
                return item.label;
            },
            // 穿梭框操作方法
            handleChange1 (newTargetKeys, direction, moveKeys) {
                console.log(newTargetKeys, 1);
                console.log(direction, 2);
                console.log(moveKeys, 3);
                this.targetKeys1 = newTargetKeys;
            },
            // 穿梭框取消
            cancelTransferMod () {
                this.transferModLoading = true;
                this.transferMod = false;
            }
        }
    };
</script>

<style lang="less">

    .saleFunnel {
        .saleFunnel-title{
            background-color: rgba(0, 0, 0, .6);
            color:#fff;
            font-size: 16px;
            line-height: 34px;
            text-align: center;
        }
        .saleFunnelPic {
            height: 330px;
            background-color: rgba(0, 0, 0, .3);
            padding: 10px 0 0;
            ul {
                width: 350px;
                height: 263px;
                margin: 0 auto;
                padding: 48px 0 50px;
                position: relative;
                background-image: url(../../../images/funnel.png);
                background-position: center;
                background-repeat: no-repeat;
                background-size: 100%;
            }
            li {
                list-style-type: none;
                text-align: center;
                position: relative;
                cursor: pointer;
                margin-top: 5px;
                .data1 {
                    position: absolute;
                    background-color: transparent;
                    left: 50%;
                    top: 50%;
                    transform: translate(-50%, -50%);

                }
                .data2 {
                    position: absolute;
                    color: #000;
                    background-color: rgba(51, 153, 204, 1);
                    left: 50%;
                    top: 50%;
                    transform: translate(-50%, -50%);
                    z-index: 3;
                    .leftArr {
                        position: absolute;
                        content: '';
                        left: 0;
                        top: 0;
                        width: 0;
                        height: 0;
                        border-bottom-color: transparent;
                        border-left-color: transparent;
                        border-style: solid;
                        z-index: 4;
                        transform: translate(-99%, 0);
                    }
                    .rightArr {
                        position: absolute;
                        content: '';
                        right: 0;
                        top: 0;
                        width: 0;
                        height: 0;
                        border-bottom-color: transparent;
                        border-right-color: transparent;
                        // border-color: #588cfb transparent transparent #588cfb;
                        border-style: solid;
                        z-index: 4;
                        transform: translate(99%, 0);
                    }
                }
                .data3 {
                    position: absolute;
                    width: 100%;
                    text-align: center;
                    color: #172741;
                    left: 0;
                    top: 0;
                    z-index: 5;
                }
            }
            .botText {
                cursor: pointer;
                margin: 10px auto 0;
                width: 200px;
                height: 40px;
                line-height: 40px;
                color: #fff;
                font-size: 14px;
                text-align: center;
                background-color: rgba(255, 255, 255, .5);
            }
        }
        .right-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: #333;
            height: 50px;

        }
        .left-info{

        }
        .right-info{
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            color: #fff;
            font-size: 12px;

        }
    }
    .customerDetailModalClass{
        height:100px;
        .ivu-modal-wrap{
            z-index: 80!important;
        }
    }
</style>
